package com.fantesy.jwtdemo.controller;

import com.fantesy.jwtdemo.entity.User;
import com.fantesy.jwtdemo.util.JWTTokenUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author fantsey
 * @date 2020/2/28
 */
@Controller
public class TestController {

    @RequestMapping("getToken")
    @ResponseBody
    public String getToken(HttpServletRequest request, HttpServletResponse response){
        User user = new User();
        user.setUserId("123456");
        user.setUsername("van");
        user.setPassword("123456");
        String token = JWTTokenUtils.getJWTToken(user);

        // 方式一： 将token保存在session中
        HttpSession session = request.getSession();
        session.setAttribute("token", token);

        // 方式二： 将token保存到cookie中，前台用户需要回传这个token，才能验证访问
        Cookie cookie = new Cookie("token", token);
        cookie.setDomain("localhost");
        response.addCookie(cookie);


        return token;
    }

    @RequestMapping("test1")
    @ResponseBody
    public String test1(HttpServletRequest request){
        return "test1";
    }

    @RequestMapping("test2")
    public String test2(HttpServletRequest request){
        return "test";
    }

    @RequestMapping("test3")
    public String test3(HttpServletRequest request){
        System.out.println("test3======================");
        return "test";
    }
}
